//
//  BTEHomeViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/5.
//

import UIKit
import SmartCodable


enum CellType {
    case rewardably
    case bombload
    case dodecatoic
}



class BTEProductViewController: BTEBaseViewController {
    
    let server = BTEProductToolNetServer()
    
    var model: BTEProductNetModel? {
        didSet {
            guard let m = model else {
                return
            }
            v.mod = m
            updateNavigationTitle(m.nonchurchgoing?.cuspid ?? "")
            v.list.isHidden = false
        }
    }
    
    var pid: String?
    
    var v: BTEProductView {
        return view as! BTEProductView
    }
    
    override func loadView() {
        view = BTEProductView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        v.list.isHidden = true
        v.bo.isHidden = true
        BTEAddressManager.stand.loadAddress()
        
        v.list.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(navigationBar.snp.bottom).offset(20)
            make.bottom.equalTo(v.loginButton.snp.top).offset(-30)
        }
        
        v.load = {[weak self] in
            self?.loadinf()
        }
        
        v.clickBy = {[weak self] in
            self?.clickBuy()
        }
        
        v.clickItem = {[weak self] idx in
            self?.clickItem(idx)
        }
        
        v.clickPro = {[weak self] in
            guard let m = self?.model?.earworms?.plectra else {
                return
            }
            BTEUrlToolsManager.shared.handleURL(m, in: self, model: nil)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadinf()
    }

}


extension BTEProductViewController {
    
    fileprivate func loadinf(){
        BTEHUD.shared.showLoader(on: view)
        server.sacculated(data: ["privileger":pid!]) {[weak self] result in
            switch result {
            case .success(let success):
                self?.v.bo.isHidden = false
                self?.v.list.isHidden = false
                self?.v.refreshfunc.endRefreshing()
                BTEHUD.shared.hide()
                self?.model = success?.sidelingwise
                break
            case .failure(let failure):
                self?.v.refreshfunc.endRefreshing()
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    
}


extension BTEProductViewController {
    
    fileprivate func clickItem(_ w: Int){
        
        guard let m = model?.ebon?[w] else {
            return
        }
        
        let can = m.chandelled ?? "0"
        let type = m.subgraphs ?? ""
        if can == "1" {
            switch type {
            case "deploitation":
                displayA(m)
            case "overprick":
                displayB(m)
            case "Vitaglass":
                displayC(m)
            case "heterostrophous":
                displayD(m)
            case "shipwards":
                displayE(m)
            default:
                break
            }
        } else {
            let type = model?.antitabloid?.subgraphs ?? ""
            m.aftermath = model?.antitabloid?.aftermath
            switch type {
            case "deploitation":
                displayA(m)
            case "overprick":
                displayB(m)
            case "Vitaglass":
                displayC(m)
            case "heterostrophous":
                displayD(m)
            case "shipwards":
                displayE(m)
            default:
                break
            }
        }
    }
    
    fileprivate func clickBuy(){
        let type = model?.antitabloid?.subgraphs ?? ""
        if type == "" {
            xidanda()
        } else {
            guard let m = model?.ebon?.filter({$0.subgraphs == type}).first else {
                return
            }
            m.aftermath = model?.antitabloid?.aftermath
            switch type {
            case "deploitation":
                displayA(m)
            case "overprick":
                displayB(m)
            case "Vitaglass":
                displayC(m)
            case "heterostrophous":
                displayD(m)
            case "shipwards":
                displayE(m)
            default:
                break
            }
        }
    }
    
}


extension BTEProductViewController {
    
    func displayA(_ m: BTEProductpeeebonbloidNetModel){
        let vc = BTEProductOneViewController.init(model: m)
        vc.pid = pid
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func displayB(_ m: BTEProductpeeebonbloidNetModel){
        let vc = BTEProductTwoViewController.init(model: m)
        vc.pid = pid
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func displayC(_ m: BTEProductpeeebonbloidNetModel){
        let vc = BTEProductThreeViewController.init(model: m)
        vc.pid = pid
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func displayD(_ m: BTEProductpeeebonbloidNetModel){
        let vc = BTEProductFoureViewController.init(model: m)
        vc.pid = pid
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func displayE(_ m: BTEProductpeeebonbloidNetModel){
        let vc = BTEProductFiveViewController.init(model: m)
        vc.pid = pid
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func xidanda(){
        BTEHUD.shared.showLoader(on: view)
        let modes:[String:String] = ["pavise":"\(model?.nonchurchgoing?.pavise ?? "")",
                                     "neurasthenias":"\(model?.nonchurchgoing?.neurasthenias ?? "")",
                                     "druggists":"\(model?.nonchurchgoing?.druggists ?? "")",
                                     "unpoetical":"\(model?.nonchurchgoing?.unpoetical ?? "")",]
        server.manificum(data: modes) {[weak self] result in
            switch result {
            case .success(let success):
                BTEHUD.shared.hide()
                if let m = success?.sidelingwise?.vyner{
                    
                  
                    let t = TrackingEvent.init(step: "8", startTimestamp: "\(Date().timeIntervalSince1970)", endTimestamp: "\(Date().timeIntervalSince1970)",orderId: self?.model?.nonchurchgoing?.neurasthenias ?? "")
                    BTELocationReporterManager.shared.reportLocation(for: t)
                    
                    
                    guard var components = URLComponents(url: URL(string: m)!, resolvingAgainstBaseURL: false) else { return }

                    // 添加公共参数
                    let additionalParams = BTEUrlToolsManager.shared.urlInfo().map { URLQueryItem(name: $0.key, value: $0.value) }
                    components.queryItems = (components.queryItems ?? []) + additionalParams

                    guard let finalURL = components.url else { return }

                    let vc = BTEWebViewViewController.init(url: finalURL.absoluteString)
                    CATransaction.begin()
                    CATransaction.setCompletionBlock {
                        if let windowScene = UIApplication.shared.windows.first  {
                            if let tab = windowScene.rootViewController as? BTEBaseTabBarController,let ve = tab.children.first as? UINavigationController {
                                ve.pushViewController(vc, animated: false)
                            }
                        }
                    }
                    self?.navigationController?.popViewController(animated: false)
                    CATransaction.commit()
                }
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    
}
